package varredor.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import varredor.concorrencia.Semaforo;
import varredor.model.Registro;

public class ArquivoCompartilhadoController {

	private static ArquivoCompartilhadoController INSTANCE;

	private static final String ARQUIVO = "arquivo.dat";

	private List<Registro> registros = new ArrayList<Registro>();

	private Semaforo semaforo = new Semaforo();

	private ArquivoCompartilhadoController() {
		super();
	}

	public static ArquivoCompartilhadoController getINSTANCE() {
		if (INSTANCE == null)
			INSTANCE = new ArquivoCompartilhadoController();

		return INSTANCE;
	}

	public void adicionarRegistro(Registro registro) {
		semaforo.DOWN();

		if (!registros.contains(registro)) {
			registros.add(registro);

			gravar();
		}

		semaforo.UP();
	}

	private void gravar() {
		ObjectOutputStream objOut = null;
		try {
			objOut = new ObjectOutputStream(new FileOutputStream(new File(ARQUIVO)));

			objOut.writeObject(registros);
			objOut.flush();
			objOut.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (objOut != null)
					objOut.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	public void carregar() {
		semaforo.DOWN();
		ObjectInputStream objInput = null;
		try {
			objInput = new ObjectInputStream(new FileInputStream(new File(ARQUIVO)));
			registros = (List<Registro>) objInput.readObject();
			objInput.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (objInput != null)
					objInput.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		semaforo.UP();
	}

	public List<Registro> retornarRegistros() {
		carregar();

		return registros;
	}
}
